<template>
  <div class="app-container">
    <el-drawer title="OQC检验详情" :visible.sync="visible" size="90%" :before-close="cancel" custom-class="demo-drawer" :append-to-body="true">
      <div style="padding: 20px;padding-top:0px">
        <div style="margin-left: 20px;">
          <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出
          </el-button>
        </div>
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-row>
            <el-col :span="6">
              <el-form-item label="产品编码：" prop="productCode">
                <el-input v-model="form.productCode" placeholder :disabled="true" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="产品名称：" prop="productName">
                <el-input v-model="form.productName" placeholder :disabled="true" />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="规格型号：" prop="productSpec">
                <el-input v-model="form.productSpec" placeholder :disabled="true" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="检验日期:" prop="inspectionDate">
                <el-date-picker clearable v-model="form.inspectionDate" type="date" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择开始日期" :disabled="true"></el-date-picker>
                <!-- :picker-options="pickerOptions" -->
                <!-- <el-input
                      v-model="form.inspectionDate"
                      placeholder
                      :disabled="optType=='add'? false:true"
                />-->
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="合同号:" prop="contractOrder">
                <el-input v-model="form.contractOrder" placeholder disabled />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="客户:" prop="customerName">
                <el-input v-model="form.customerName" placeholder disabled />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="技术分解单号：" prop="tecDecNumber">
                <el-input v-model="form.tecDecNumber" placeholder :disabled="optType == 'add' ? false : true" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="报检数量：" prop="quinspection">
                <el-input-number :controls="false" :disabled="true" v-model="form.quinspection" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="检验类型" prop="oqcInspectionType">
                <el-select v-model="form.oqcInspectionType" placeholder="请选择检验类型" :disabled="true">
                  <el-option label="全检" value="0"></el-option>
                  <el-option label="抽检" value="1"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" v-if="form.oqcInspectionType == '1'">
              <el-form-item label="抽样数量" prop="samplingQuantity">
                <el-input-number :controls="false" v-model="form.samplingQuantity" :disabled="optType == 'add' ? false : true" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="合格数量" prop="qualifiedQuantity">
                <el-input v-model="form.qualifiedQuantity" placeholder :disabled="optType == 'add' ? false : true" @change="(value) => autoInput(value, 'qualifiedQuantity', 'unqualifiedQuantity')" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="不合格数量" prop="unqualifiedQuantity">
                <el-input v-model="form.unqualifiedQuantity" placeholder :disabled="optType == 'add' ? false : true" @change="(value) => autoInput(value, 'unqualifiedQuantity', 'qualifiedQuantity')" />
              </el-form-item>
            </el-col>
            <!-- <el-col :span="6">
              <el-form-item label="质检方案" prop="InspectionScheme">
                <el-select v-model="form.InspectionScheme" filterable placeholder="请选择" :disabled="true">
                  <el-option v-for="item in InspectionSchemeList" :key="item.fid" :label="item.fname"
                    :value="item.fid" />
                </el-select>
              </el-form-item>
            </el-col> -->
          </el-row>
          <el-row v-if="snCodeAllList && snCodeAllList.length > 0">
            <el-col :span="24">
              <el-form-item label="SN码">
                <div>
                  <el-checkbox-group v-model="snList">
                    <el-checkbox v-for="item in snCodeAllList" :label="item" :key="item">{{ item }}</el-checkbox>
                  </el-checkbox-group>
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-table v-loading="loading1" :data="templateList" :span-method="objectSpanMethod">
              <el-table-column label="类型" align="center" prop="indexType" width="160px">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.mes_index_type" :value="scope.row.indexType" />
                </template>
              </el-table-column>
              <el-table-column type="index" width="50"></el-table-column>
              <el-table-column label="检测项目" align="center" prop="indexName" width="260px" />
              <el-table-column align="center" prop="checkResult" width="240px" label="检查结果">
                <template slot-scope="scope">
                  <div>
                    <div style="font-size:20px">{{ scope.row.checkResult == '0' ? "×" : scope.row.checkResult == '1' ?
                      "√" : "--" }}</div>
                    <div v-if="scope.row.attrObj.type == '2'">
                      <div class="mInput">
                        <span>标准值</span>
                        <span>{{ scope.row.attrObj.standard }}：</span>
                        <span>{{ scope.row.attrObj.num }}</span>
                      </div>
                    </div>
                    <ul v-if="scope.row.attrObj.type == '4'">
                      <li class="mInput">
                        <span>长</span>
                        <span>{{ scope.row.attrObj.lStandard }},</span>
                        <span>{{ scope.row.attrObj.lNum }}</span>
                      </li>
                      <li class="mInput">
                        <span>宽</span>
                        <span>{{ scope.row.attrObj.wStandard }},</span>
                        <span>{{ scope.row.attrObj.wNum }}</span>
                      </li>
                      <li class="mInput">
                        <span>高</span>
                        <span>{{ scope.row.attrObj.hStandard }},</span>
                        <span>{{ scope.row.attrObj.hNum }}</span>
                      </li>
                    </ul>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-row>
          <el-row>
            <el-col :span="24" class="imgDiv">
              <el-form-item label="检验结果" prop="checkResult">
                <el-radio-group v-model="form.checkResult">
                  <el-radio :label="1">√</el-radio>
                  <el-radio :label="0">×</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-table-column label="异常描述" align="center" prop="describeData">
              <template slot-scope="scope">
                <el-input v-model="scope.row.describeData" placeholder type="textarea" />
              </template>
            </el-table-column>
            <!-- :disabled="form.state =='0'?false:true" -->
            <el-col :span="16">
              <el-form-item label="备注:" prop="remark">
                <!--                <el-input-->
                <!--                  v-model="form.remark"-->
                <!--                  type="textarea"-->
                <!--                  placeholder="输入备注"-->
                <!--                  style="width: 450px; height: 50px"-->
                <!--                ></el-input>-->
                <el-input v-model="form.remark" placeholder="输入备注" type="textarea" />
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 不合格品异常记录列表 -->
          <div v-if="form.checkResult == 0">
            <el-form-item label="不合格品处理方式" prop="repairState">
              <span>
                ：
                {{ form.repairState == '1' ? '返工' : form.repairState == '2' ? "返修" : "--" }}
              </span>
            </el-form-item>

            <el-form-item label="异常记录">
              <el-table :data="exceptionLogList">
                <el-table-column label="类型选择" align="center" prop="indexType">
                  <template slot-scope="scope">
                    <el-select v-model="scope.row.indexType" placeholder="请选择检测项类型" clearable>
                      <el-option v-for="dict in errorTypeList" :key="dict.indexType" :label="dict.indexTypeName" :value="dict.indexTypeName" />
                    </el-select>
                  </template>
                </el-table-column>

                <el-table-column label="异常描述" align="center" prop="describeData">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.describeData" placeholder type="textarea" />
                  </template>
                </el-table-column>
                <el-table-column label="文件上传" align="center" prop="fileName">
                  <template slot-scope="scope">
                    <ImageUpload :limit="1" :value="scope.row.fileName" :fileSize="15" @input="(url) => handleImgUplaoded(url, scope.$index)" @onRemoved="(url) => handleImgRemoved(url, scope.$index)"></ImageUpload>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                  <template slot-scope="scope">
                    <el-button size="medium" type="text" icon="el-icon-circle-plus-outline" @click="errorAdd(item)"></el-button>
                    <el-button v-if="scope.$index != 0" size="medium" type="text" icon="el-icon-remove-outline" @click="errorDel(scope.$index)"></el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import { qcschemeAll } from "@/api/mes/qc/iqc";
import { getFqcDtoInfo, exportFqcInfo, exportFqcInfo2 } from "@/api/mes/qc/fqc";
import { getDetail } from "@/api/mes/qc/qcOqcInspection";
import { blobValidate } from "@/utils/hici";
import { Message, Loading } from "element-ui";
import { saveAs } from "file-saver";

let downloadLoadingInstance;
export default {
  name: "replenishmenqqqqt",

  dicts: ["mes_index_type"],
  data() {
    return {
      // 遮罩层
      loading: true,
      visible: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      form: {},
      optType: "view",
      // 弹出层标题

      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      // 模板列表
      templateList: [],
      loading1: false,
      spanArr: [],
      // 异常记录列表
      exceptionLogList: [{}],
      // 不合格数
      failedSncode: [],
      // 首页列表信息
      QcFqcAcInspectionHead: {},
      errorTypeList: [],
      snCodeAllList: [],
      //质检方案
      InspectionSchemeList: [],
      snList: [],
      rules: {
        snCode: [{ required: true, message: "SN码不能为空", trigger: "blur" }],
        unqualifiedCode: [
          { required: true, message: "不合格数量不能为空", trigger: "blur" }
        ],
        qualifiedCode: [
          { required: true, message: "合格数量不能为空", trigger: "blur" }
        ],
        checkResult: [
          { required: true, message: "检验结果不能为空", trigger: "change" }
        ],

        headEndCheckType: [
          { required: true, message: "类型不能为空", trigger: "change" }
        ]
      },
      formDetail: {}
    };
  },
  created() {
    // this.getList();
  },

  methods: {
    init(row) {
      this.visible = true;
      // 调用查询质检方案list接口
      this.getQualityinspection();
      this.getList(row);
    },
    //查询质检方案list
    getQualityinspection() {
      qcschemeAll().then((res) => {
        if (res.code == 200) {
          this.InspectionSchemeList = res.data;
        } else {
          this.InspectionSchemeList = []
        }
      }).catch(() => {
        this.InspectionSchemeList = []
      });
    },
    /** 查询产品制程物料BOM列表 */
    getList(row) {
      this.QcFqcAcInspectionHead = row;
      getDetail(row.id).then(res => {
        console.log(res, "[]========res=====");
        let list = [];
        this.formDetail = { ...res.data };
        this.formDetail = { ...res.data, ftext1: res.data.qcOqcInspection.tecDecNumber };

        this.form = {
          ...res.data.qcInspectionResult,
          ...res.data.qcOqcInspection
        };
        // this.form.remark = res.data.qcOqcInspection.remark;
        for (let i = 0; i < res.data.qcOqcInspectionItemList.length; i++) {
          let obj = res.data.qcOqcInspectionItemList[i];
          // let attrList = res.data.qcOqcInspectionItemList[i].attr2;
          // obj.resultList = JSON.parse(attrList);
          obj.attrObj = obj.attr1 ? JSON.parse(obj.attr1) : { type: "0" };
          if (obj.attrObj.type == "2") {
            let attr2 = res.data.qcOqcInspectionItemList[i].attr2
              ? JSON.parse(res.data.qcOqcInspectionItemList[i].attr2)
              : {};
            obj.attrObj.num = attr2.num;
          }
          if (obj.attrObj.type == "4") {
            let attr2 = res.data.qcOqcInspectionItemList[i].attr2
              ? JSON.parse(res.data.qcOqcInspectionItemList[i].attr2)
              : {};
            obj.attrObj.lNum = attr2.lNum;
            obj.attrObj.wNum = attr2.wNum;
            obj.attrObj.hNum = attr2.hNum;
          }

          list.push(obj);
        }
        console.log(list, "=============List=============");
        this.exceptionLogList = res.data?.qcInspectionResult.exceptionLogList;
        this.templateList = list || [];
        this.snCodeAllList = this.snList = res.data.snList || [];

        // this.open = true;
        this.title = "查看检验详情";
        this.optType = "view";
        this.getSpanArr(list || []);
      });
    },
    cancel() {
      this.formDetail = {};
      this.visible = false;
      this.routeproductbomList = [];
    },
    // 行合并
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        const _row = this.spanArr[rowIndex]; // 合并行数
        const _col = this.spanArr[rowIndex] > 0 ? 1 : 0; // 合并的列数
        return {
          rowspan: _row,
          colspan: _col
        };
      }
    },
    // 按照类型合并
    getSpanArr(data) {
      this.spanArr = []; // tip: 后台获取完成数据后，一定要重置spanArr=[],避免出现合并混乱！！！！！
      if (data.length > 0) {
        for (let i = 0; i < data.length; i++) {
          // 当为第一行时
          if (i === 0) {
            this.spanArr.push(1);
            this.pos = 0;
          } else {
            // 判断当前值是否与上一行的【名称】相等，相等则进行合并
            if (data[i].indexType === data[i - 1].indexType) {
              this.spanArr[this.pos] += 1; // 合并单元格：合并的行数 +1
              this.spanArr.push(0); // 0代表单元格是不需要显示, 已经被合并的单元格
            } else {
              this.spanArr.push(1); // 1代表当前这行的数据需要被显示
              this.pos = i;
            }
          }
        }
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      const newFormDetail = this.deepClone(this.formDetail)
      newFormDetail.qcOqcInspectionItemList = newFormDetail.qcOqcInspectionItemList.map(item => {
        let obj = item
        //let findItem = this.dict.type.mes_index_type.find(val => val.value === item.indexType)
        //obj.indexType = findItem ? findItem.label : ''
        return obj
      })
      let query = { ...newFormDetail };
      downloadLoadingInstance = Loading.service({
        text: "正在下载数据，请稍候",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      exportFqcInfo2(query)
        .then(async data => {
          console.log(query, "======");
          const isBlob = blobValidate(data);
          if (isBlob) {
            const blob = new Blob([data]);
            saveAs(blob, `OQC检验详情.xlsx`);
          } else {
            const resText = await data.text();
            const rspObj = JSON.parse(resText);
            const errMsg =
              errorCode[rspObj.code] || rspObj.msg || errorCode["default"];
            Message.error(errMsg);
          }
          downloadLoadingInstance.close();
        })
        .catch(r => {
          console.error(r);
          Message.error("下载文件出现错误，请联系管理员！");
          downloadLoadingInstance.close();
        });
      // this.downloadDetail(
      //   "mes/qc/iqc/export/iqcInfo",
      //   {
      //     ...this.form
      //   },
      //   `iqcDetail_${new Date().getTime()}.xlsx`
      // );
      // this.download('/mes/qc/oqcRecords/export/detail ', {
      //     ...this.formDetail
      //   }, `expression_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
